import 'dart:io';

import 'package:base_lib/common/base/base_bloc_page.dart';
import 'package:base_lib/common/index.dart';
import 'package:base_lib/common/widget/peach_button.dart';
import 'package:base_lib/index.dart';
import 'package:base_lib/router/index.dart';
import 'package:base_lib/theme/theme_global.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:fsuper/fsuper.dart';
import 'package:image_picker/image_picker.dart';
import 'bloc.dart';
import 'package:doctor_login_lib/login/entity/doctor_login_entity.dart'
    as DoctorLoginBean;
import 'package:base_lib/dictionary/entity/medical_section_entity.dart'
    as SectionBean;
import 'package:base_lib/dictionary/entity/doctor_title_entity.dart'
    as DoctorTitleBean;
import 'package:base_lib/dictionary/entity/doctor_practice_entity.dart'
    as DoctorPracticeBean;

///完善个人信息
class SetUserInfoPage
    extends BaseBlocPage<SetUserInfoBloc, _SetUserInfoPageState> {
  SetUserInfoPage(Parameters parameters) : super(parameters);

  @override
  _SetUserInfoPageState generateThemeState() {
    return _SetUserInfoPageState();
  }
}

class _SetUserInfoPageState extends BaseBlocPageState<SetUserInfoBloc> {
  @override
  Widget buildChild(BuildContext context, MTheme theme) {
    return Material(
      child: Scaffold(
          appBar: AppBar(
            leading: BackButton(
              onPressed: () {
                Routers.pop(context);
              },
            ),
            title: Text("完善个人信息"),
            centerTitle: true,
          ),
          body: Container(
            color: Colors.white,
            height: double.infinity,
            width: double.infinity,
            child: SingleChildScrollView(
              child: Column(
                children: [
                  Container(
                    color: ColorUtil.color("#EAF5FF"),
                    width: double.infinity,
                    height: 32.0,
                    alignment: Alignment.center,
                    child: Text(
                      "为了给您提供更好的服务请您填写真实的个人信息",
                      style: TextStyle(
                          color: theme.themeColor.themeColor,
                          fontWeight: FontWeight.w400,
                          fontSize: theme.themeFontSize.fontSizeSmall),
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.symmetric(vertical: 20, horizontal: 24),
                    child: SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Container(
                            margin: EdgeInsets.only(bottom: 10.0),
                            width: double.infinity,
                            child: Row(
                              children: [
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        "工作照",
                                        textAlign: TextAlign.left,
                                        style: TextStyle(
                                            color: ColorUtil.color("#797979"),
                                            fontSize: 15),
                                      ),
                                      Padding(
                                        padding:
                                            const EdgeInsets.only(top: 8.0),
                                        child: Text(
                                          "*工作照将作为您的头像显示，建议上传正方形的清晰照片（建议大小500x500）",
                                          style: TextStyle(
                                              color: ColorUtil.color("#797979"),
                                              fontSize: 11),
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                                10.hGapDp,
                                StreamBuilder(
                                  stream: bloc.header,
                                  builder: (context,
                                      AsyncSnapshot<String> snapshot) {
                                    return BaseImgPicker<String>(
                                      snapshot.data,
                                      onSuccess: (path) {
                                        bloc.saveDoctorPhoto(context, path);
                                      },
                                      onDelete: (data) {
                                        bloc.deleteDoctorPhoto(context);
                                      },
                                      onFailure: (err) {},
                                      tip: "工作照",
                                      imagePath: snapshot?.data ?? '',
                                      showLoading: (!snapshot.hasData ||
                                          snapshot.data == "-"),
                                    );
                                  },
                                ),
                              ],
                            ),
                          ),
                          Divider(height: 1),
                          _buildName(theme),
                          _buildGroup(theme),
                          Divider(height: 1),
                          _buildPractice(theme),
                          _buildDepartment(theme),
                          Padding(
                            padding: const EdgeInsets.only(top: 10.0),
                            child: Divider(height: 1),
                          ),
                          _buildJobTitle(theme),
                          _buildTreatDiseases(theme),
                          _buildGood(theme),
                          Padding(
                            padding: const EdgeInsets.only(top: 10.0),
                            child: Divider(height: 1),
                          ),
                          _buildInfo(theme),
                          StreamBuilder(
                            stream: bloc.loadingStatus,
                            initialData: false,
                            builder: (context, AsyncSnapshot<bool> loading) {
                              return Padding(
                                padding: const EdgeInsets.only(top: 40.0),
                                child: peachButtonBuilder(
                                  onTap: () {
                                    if (!loading.data)
                                      bloc.updateUserInfo(context);
                                  },
                                  text: loading.data ? "请求中..." : "下一步",
                                ),
                              );
                            },
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          )),
    );
  }

  @override
  SetUserInfoBloc generateBloc() {
    return SetUserInfoBloc();
  }

  @override
  ignoreWindowWidget() => true;

  ///姓名输入框
  Widget _buildName(MTheme theme) {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(top: 10),
      child: StreamBuilder(
        stream: bloc.name,
        builder: (context, AsyncSnapshot<String> snapshot) {
          return Row(
            children: [
              Expanded(
                child: Text(
                  "姓名",
                  style: TextStyle(
                      color: theme.themeColor.themeTextTitleColor,
                      fontSize: 16),
                ),
              ),
              Expanded(
                child: TextField(
                  onChanged: (value) {
                    bloc.editNameChanged(value);
                  },
                  controller: TextEditingController(text: snapshot?.data ?? ""),
                  cursorColor: Colors.grey,
                  textAlign: TextAlign.right,
                  strutStyle: StrutStyle(
                      fontSize: theme.themeFontSize.fontSizeBig, height: 1),
                  style: TextStyle(
                      color: Colors.black,
                      fontSize: theme.themeFontSize.fontSizeBig),
                  decoration: InputDecoration(
                    border: InputBorder.none,
                    hintText: "*请输入姓名",
                    hintStyle: TextStyle(color: Colors.grey, fontSize: 16),
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  ///医院(诊所)输入框
  Widget _buildGroup(MTheme theme) {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(top: 10),
      child: StreamBuilder(
        stream: bloc.hospital,
        builder: (context, AsyncSnapshot<String> snapshot) {
          return Row(
            children: [
              Expanded(
                child: Text(
                  "医院(诊所)",
                  style: TextStyle(
                      color: theme.themeColor.themeTextTitleColor,
                      fontSize: 16),
                ),
              ),
              10.hGapDp,
              Expanded(
                child: TextField(
                  onChanged: (value) {
                    bloc.editHospitalChanged(value);
                  },
                  controller: TextEditingController(text: snapshot?.data ?? ""),
                  cursorColor: Colors.grey,
                  textAlign: TextAlign.right,
                  strutStyle: StrutStyle(
                      fontSize: theme.themeFontSize.fontSizeBig, height: 1),
                  style: TextStyle(
                      color: Colors.black,
                      fontSize: theme.themeFontSize.fontSizeBig),
                  decoration: InputDecoration(
                    border: InputBorder.none,
                    hintText: "*请输入医院(诊所)",
                    hintStyle: TextStyle(color: Colors.grey, fontSize: 16),
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  ///执业类型
  Widget _buildPractice(MTheme theme) {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(top: 20),
      child: StreamBuilder(
        stream: bloc.doctorPractice,
        initialData: null,
        builder: (context, AsyncSnapshot<String> snapshot) {
          return Row(
            children: [
              Expanded(
                child: Text(
                  "执业类型",
                  style: TextStyle(
                      color: theme.themeColor.themeTextTitleColor,
                      fontSize: 16),
                ),
              ),
              10.hGapDp,
              Expanded(
                child: GestureDetector(
                    onTap: () {
                      FocusScope.of(context).requestFocus(FocusNode());
                      bloc.getPractice().then((titles) {
                        if (titles.isNotEmpty) {
                          showItemChooser<DoctorPracticeBean.Data>(
                              context, theme, titles, (bean) {
                            return bean.dictName;
                          }).then((value) => bloc.setDoctorPractice(value));
                        }
                      });
                    },
                    child: Text(snapshot.hasData ? snapshot.data : "点击选择",
                        textAlign: TextAlign.right,
                        style: TextStyle(color: Colors.grey, fontSize: 16))),
              ),
              Icon(
                Icons.keyboard_arrow_right,
                color: Colors.grey[400],
              ),
            ],
          );
        },
      ),
    );
  }

  ///科室
  Widget _buildDepartment(MTheme theme) {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(top: 20),
      child: StreamBuilder(
        stream: bloc.section,
        builder: (context, AsyncSnapshot<String> snapshot) {
          return Row(
            children: [
              Expanded(
                child: Text(
                  "科室",
                  style: TextStyle(
                      color: theme.themeColor.themeTextTitleColor,
                      fontSize: 16),
                ),
              ),
              10.hGapDp,
              Expanded(
                child: GestureDetector(
                    onTap: () {
                      FocusScope.of(context).requestFocus(FocusNode());
                      bloc.chooseSection(context);
                    },
                    child: Text(snapshot.hasData ? snapshot.data : "点击选择",
                        textAlign: TextAlign.right,
                        style: TextStyle(color: Colors.grey, fontSize: 16))),
              ),
              Icon(
                Icons.keyboard_arrow_right,
                color: Colors.grey[400],
              ),
            ],
          );
        },
      ),
    );
  }

  ///职称
  Widget _buildJobTitle(MTheme theme) {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(top: 20),
      child: StreamBuilder(
        stream: bloc.doctorTitle,
        initialData: null,
        builder: (context, AsyncSnapshot<String> snapshot) {
          return Row(
            children: [
              Expanded(
                child: Text(
                  "职称",
                  style: TextStyle(
                      color: theme.themeColor.themeTextTitleColor,
                      fontSize: 16),
                ),
              ),
              10.hGapDp,
              Expanded(
                child: GestureDetector(
                    onTap: () {
                      FocusScope.of(context).requestFocus(FocusNode());
                      bloc.getTitles().then((titles) {
                        if (titles.isNotEmpty) {
                          showItemChooser<DoctorTitleBean.Data>(
                              context, theme, titles, (bean) {
                            return bean.dictName;
                          }).then((value) => bloc.setDoctorTitle(value));
                        }
                      });
                    },
                    child: Text(snapshot.hasData ? snapshot.data : "点击选择",
                        textAlign: TextAlign.right,
                        style: TextStyle(color: Colors.grey, fontSize: 16))),
              ),
              Icon(
                Icons.keyboard_arrow_right,
                color: Colors.grey[400],
              ),
            ],
          );
        },
      ),
    );
  }

  ///专治疾病
  Widget _buildTreatDiseases(MTheme theme) {
    return Container(
      width: double.infinity,
      height: 20,
      margin: EdgeInsets.only(top: 24),
      child: StreamBuilder(
        stream: bloc.disease,
        builder: (context, AsyncSnapshot<String> snapshot) {
          return Row(
            children: [
              Expanded(
                child: Text(
                  "专治疾病",
                  style: TextStyle(
                      color: theme.themeColor.themeTextTitleColor,
                      fontSize: 16),
                ),
              ),
              10.hGapDp,
              Expanded(
                child: GestureDetector(
                    onTap: () {
                      FocusScope.of(context).requestFocus(FocusNode());
                      bloc.jump2Disease(context);
                    },
                    child: Text(snapshot.hasData ? snapshot.data : "点击填写专治疾病",
                        textAlign: TextAlign.right,
                        overflow: TextOverflow.clip,
                        style: TextStyle(color: Colors.grey, fontSize: 16))),
              ),
              5.hGapDp,
              Icon(
                Icons.keyboard_arrow_right,
                color: Colors.grey[400],
              ),
            ],
          );
        },
      ),
    );
  }

  ///擅长
  Widget _buildGood(MTheme theme) {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(top: 20),
      child: StreamBuilder(
        stream: bloc.goodAt,
        builder: (context, AsyncSnapshot<String> snapshot) {
          return Row(
            children: [
              Expanded(
                child: Text(
                  "擅长",
                  style: TextStyle(
                      color: theme.themeColor.themeTextTitleColor,
                      fontSize: 16),
                ),
              ),
              10.hGapDp,
              Expanded(
                child: GestureDetector(
                    onTap: () {
                      FocusScope.of(context).requestFocus(FocusNode());
                      bloc.jump2GoodAt(context);
                    },
                    child: Text(snapshot.hasData ? snapshot.data : "点击填写擅长",
                        textAlign: TextAlign.right,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(color: Colors.grey, fontSize: 16))),
              ),
              Icon(
                Icons.keyboard_arrow_right,
                color: Colors.grey[400],
              ),
            ],
          );
        },
      ),
    );
  }

  ///简介
  Widget _buildInfo(MTheme theme) {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(top: 20),
      child: StreamBuilder(
        stream: bloc.briefDesc,
        builder: (context, AsyncSnapshot<String> snapshot) {
          return Row(
            children: [
              Expanded(
                child: Text(
                  "简介",
                  style: TextStyle(
                      color: theme.themeColor.themeTextTitleColor,
                      fontSize: 16),
                ),
              ),
              10.hGapDp,
              Expanded(
                child: GestureDetector(
                    onTap: () {
                      FocusScope.of(context).requestFocus(FocusNode());
                      bloc.jump2BriefDesc(context);
                    },
                    child: Text(snapshot.hasData ? snapshot.data : "点击填写个人简介",
                        textAlign: TextAlign.right,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(color: Colors.grey, fontSize: 16))),
              ),
              Icon(
                Icons.keyboard_arrow_right,
                color: Colors.grey[400],
              ),
            ],
          );
        },
      ),
    );
  }

  Future<T> showItemChooser<T>(BuildContext context, MTheme theme,
      List<T> titles, Function(T) getTitle) {
    var pos = 0;
    return showMyBottomSheet<T>(
        context: context,
        builder: (context) {
          return Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(20), topRight: Radius.circular(20)),
              color: Colors.white,
            ),
            height: ScreenAdapter.screenHeightDp * 0.4,
            child: Column(
              children: [
                SizedBox(
                  height: 10,
                ),
                Row(
                  children: [
                    FlatButton(
                      onPressed: () {
                        Navigator.pop(context, titles[pos]);
                      },
                      child: Text(
                        "确定",
                        style: TextStyle(
                          color: theme.themeColor.themeColor,
                        ),
                      ),
                    ),
                    Spacer(),
                    FlatButton(
                      onPressed: () {
                        Navigator.pop(context);
                      },
                      child: Text(
                        "取消",
                        style: TextStyle(
                          color: Colors.red,
                        ),
                      ),
                    )
                  ],
                ),
                Divider(
                  height: 1,
                ),
                Expanded(
                  child: ListWheelScrollView(
                      itemExtent: 50,
                      overAndUnderCenterOpacity: 0.3,
                      children: titles.map((item) {
                        return Container(
                          margin: EdgeInsets.symmetric(
                              vertical: 10, horizontal: 30),
                          alignment: Alignment.center,
                          child: Text(
                            getTitle(item),
                            style: TextStyle(fontSize: 16),
                          ),
                        );
                      }).toList(),
                      onSelectedItemChanged: (value) {
                        pos = value;
                      }),
                ),
              ],
            ),
          );
        });
  }
}
